<template>
  <!-- 页脚操作栏 -->
  <div class="btn_box tool-btns--fixed page-btn-right-top">
    <BasePrintButton v-if="editModel == 2" :beforePrintFn="() => getPritContent()" class="button_right" />
    <a-button :loading="loading[0]" :disabled="loading[1]" v-if="(editModel == 1 && form.status == 0) || editModel == 0" type="primary" class="button_right" @click="handleSubmit('DRAFT')">保存草稿</a-button>
    <a-button :loading="loading[1]" :disabled="loading[0]" v-if="(editModel == 1 && form.status == 0) || editModel == 0" type="primary" class="button_right" @click="handleSubmit('SUBMITTED')">提交</a-button>
    <a-button v-if="editModel == 3" type="primary" class="button_right" @click="handleValidate">提交</a-button>
    <a-button v-if="editModel == 4" type="primary" class="button_right" @click="handleGenerate">提交</a-button>
    <a-button type="primary" @click="closeA">关闭</a-button>
  </div>
</template>

<script>
import BasePrintButton from '@/components/BasePrintButton' // 打印按钮
import { technicalProblemNoticePrint, createTechnicalProblemNotice, updateTechnicalProblemNotice, technicalProblemNoticeUpdateStatus } from "@/api/technology"

export default {
  name: 'a' + Date.now(),
  components: {
    BasePrintButton
  },
  props: {
    // 请求加载框
    loading: {
      type: Object,
      default: () => ({ 0: false, 1: false })
    },
    // 表单
    form: {
      type: Object,
      default: () => ({})
    },
    // 操作类型：0 新增，1 编辑，2 查看，3 验证，4 生成整改单
    editModel: {
      type: [String, Number],
      default: () => '0'
    },
    // 业务id
    id: {
      type: String,
      default: () => ''
    },
    // 请求api
    api: {
      type: Object,
      default: () => null
    }
  },
  data() {
    return {
      statusCode: '' // 审批状态
    }
  },
  methods: {
    closeA() {
      this.$router.replace({
        path: '/technical/technicalInspection/rectificationNotice'
      })
    },
    /**
     * @description: 获取打印内容
     * @return {*}
     */
    getPritContent() {
      return technicalProblemNoticePrint(this.id).then((res) => {
        if (res.data.content) {
          return res.data.content
        }
      })
    },
    /**
     * @description: 保存草稿或提交
     * @param {*} status：SUBMITTED：提交；DRAFT：保存草稿
     * @return {*}
     */
    handleSubmit(status) {
      // 提交校验表单
      if (status === 'SUBMITTED') {
        this.$parent.$children?.[0]?.$refs.ruleForm.validate((e) => {
          if (e) {
            if (!this.form.problems?.length) {
              this.$message.warning('问题信息列表不能为空！')
              return
            }
            this.$confirm({
              titile: '提示',
              content: '确认提交，提交后不可撤回？',
              onOk: () => {
                return this.submit(status)
              }
            })
          }
        })
      } else {
        // 保存只校验受检单位
        this.$parent.$children?.[0]?.$refs.ruleForm.validateField('inspectedUnitId',(e)=> {
          if(!e){
            this.submit(status)
          }
        })
      }
    },
    /**
     * @description: 提交表单
     * @param {*} status
     * @return {*}
     */
    submit(status) {
      let statusCode = { DRAFT: 0, SUBMITTED: 1 }[status]
      let that = this
      let api = [createTechnicalProblemNotice,updateTechnicalProblemNotice][that.editModel] // 根据操作切换url地址

      // 提交表单
      that.loading[statusCode] = true
      let form = that.$clone(that.form),
      sendUserIds = that.$clone(that.form.sendUserIds);
      // if(form.tageCode === 'PD') {
      //   // form.inspectedUnitId = form.orgId
      //   form.inspectedUnitName = form.inspectedUnitName + '/' + form.projectName
      // }
      if(sendUserIds && sendUserIds?.length){
        if(Array.isArray(sendUserIds)){    //  //后端返回的是数组，要传给后端字符串
          form.sendUserIds = sendUserIds.join(','); 
        }else{
          form.sendUserIds = sendUserIds;   //删除之后变为字符串了
        }           
      } 
      form.submitStatus = statusCode
      // 将form.checks中需要处理的表单放进problem，且删除根对象相应表单
      if (form.problems?.length) {
        for (let item of form.problems) {
          // if(!item.status ) {
          //   item.status = 1
          // }
          // 转译打点坐标
          if (Array.isArray(item?.coordinate)) {
            item.coordinate = item.coordinate?.map((i) => i.x + ',' + i.y)?.join(';')
          }
          if(item.sendUserIds&&Array.isArray(item.sendUserIds)){    //  //后端返回的是数组，要传给后端字符串
            item.sendUserIds =  item.sendUserIds.join(',');
          }
        }
      }
      delete form.status
      return api(form)
        .then((res) => {
          if (res.code === "0" || res.data.code === "0") {
            that.loading[statusCode] = false
            that.$message.success(['保存', '提交'][statusCode] + '成功！')
            that.$multiTab.close()
          }
        })
        .finally(() => {
          that.loading[statusCode] = false
        })
    },
    /**
     * @description: 验证结果
     */
    handleValidate() {
      if (!this.form.status){
        this.$message.warning('请选择验证结果');
        return false
      }
      console.log('this.form.statusthis.form.status',this.form.status)
      this.$confirm({
        title: '提示',
        content: '确认提交，提交后不可撤回？',
        onOk: () => {
          return technicalProblemNoticeUpdateStatus({
              id: this.id,
              status: this.form.status
            })
            .then((res) => {
                this.$message.success('验证成功！')
                this.$router.back()
            })
        }
      })
    },
    /**
     * @description: 生成整改单
     */
    handleGenerate() {
      this.$parent.$children?.[0]?.$refs.ruleForm.validate((e) => {
        if (e) {
          if (!this.form.checks?.length) {
            this.$message.warning('问题信息列表不能为空！')
            return
          }
          this.$confirm({
            title: '提示',
            content: '确认提交，提交后不可撤回？',
            onOk: () => {
              return this.api?.generate(this.form).then((res) => {
                if (res.data.code === 200) {
                  this.$message.success('生成成功！')
                  this.$close()
                }
              })
            }
          })
        }
      })
    }
  }
}
</script>